package com.longtop.framework.sys.login.web;

import java.util.HashMap;
import java.util.List;

import com.longtop.framework.base.BaseAction;
import com.longtop.framework.common.Constant;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.sys.log.service.LogService;
import com.longtop.framework.sys.login.service.LoginService;
import com.longtop.framework.sys.user.model.TSysUser;
import com.longtop.framework.util.BeanUtil;
import com.longtop.framework.util.SpringBeanFactory;
import com.longtop.framework.util.StringUtil;
import com.longtop.framework.util.WebUtil;
import com.longtop.intelliweb.action.IActionContext;
import com.longtop.intelliweb.action.IInitContext;
import com.longtop.intelliweb.view.Dataset;
import com.longtop.intelliweb.view.ListDropDown;
import com.longtop.intelliweb.view.ListDropDownItem;
import com.longtop.intelliweb.view.Text;

/**
 * 
 * @author 胡砥峰
 * @version 1.0
 * @修改：SJH-20110217
 * 
 */
public class MainAction extends BaseAction {

	/**
	 * 
	 */
	public void init(IInitContext context) {

		// 取得页面传来的菜单数据集对象
		Dataset ds_menu_all = context.getDataset("Dataset_Menu_All");
		if (!WebUtil.validateDatasetExist(this, ds_menu_all, "Dataset_Menu_All")) {
			return;
		}
		LoginService loginService = SpringBeanFactory.getBean(LoginService.BEAN_ID);

		// 1.登陆成功后，从session中取出用户代码，关联用户角色表及权限表，取出该用户拥有的菜单权限
		SessionObject sessionObject = this.getSessionObject(context);

		// 得到菜单代码串
		List authOperMenuList = sessionObject.getAuthOperMenuList();

		// 根据菜单代码串从菜单表中取出菜单信息
		// List menuList = loginService.getUserMenuLevel2(authOperMenuList,
		// context);
		List menuListAll = loginService.getUserMenu(authOperMenuList, context);

		// 从业务逻辑层取出的菜单列表，加到Web层的菜单数据集中
		try {
			// BeanUtil.listToDataset(menuList, ds_menu);
			BeanUtil.listToDataset(menuListAll, ds_menu_all);
		} catch (Exception e) {
			e.printStackTrace();
			hintErrorMessage(e.getMessage());
		}

		// 读取当前用户的快速入口list
		HashMap hashMap = new HashMap();
		hashMap.put("roleId", sessionObject.getRoleId());
		hashMap.put("userId", sessionObject.getUserId());
		List shortcutList = loginService.queryForListByIbatis("sysUserSql.selectShortcutList", hashMap);
		context.getRequest().getSession().setAttribute("shortcutList", shortcutList);
		// 当前用户的快速入口list传给前台。

		// 传当前用户的 角色列表 到前台
		List userRoleList = loginService.queryForListByIbatis("sysUserSql.selectUserRoleList", sessionObject.getUserId());

		// 若只有一个角色则隐藏切合角色下拉框：
		if (userRoleList.size() <= 1 && !sessionObject.getUserId().equals(Constant.ADMIN)) {
			Text userRoleId = (Text) context.getControl("Text_userRoleId");
			userRoleId.setVisible("false");
			return;
		}
		ListDropDown userRoleListDropDown = (ListDropDown) context.getControl("ListDropDown_UserRole");
		for (int i = 0; i < userRoleList.size(); i++) {
			HashMap hm = (HashMap) userRoleList.get(i);

			ListDropDownItem listDropDownItem = new ListDropDownItem();
			listDropDownItem.setLabel((String) hm.get("ROLE_NAME"));
			listDropDownItem.setName((String) hm.get("ROLE_ID"));
			listDropDownItem.setValue((String) hm.get("ROLE_ID"));

			userRoleListDropDown.addItem(listDropDownItem);
		}
	}

	/**
	 * 用户注销
	 * 
	 * @param context
	 *            intelliWeb Web层上下文对象
	 */
	public void logout(IActionContext context) {

		if (context.getRequest().getSession().getAttribute(Constant.SESSION_OBJECT) != null) {
			// 取得session对象
			SessionObject sessionObject = (SessionObject) context.getRequest().getSession().getAttribute(Constant.SESSION_OBJECT);

			// 2010-10-21；胡砥峰新增内容：注销的时候，保存当前角色，作为下一次登陆的首选角色 /暫時沒有多角色
			// if (sessionObject != null) {
			// BaseService baseService = this.getBean(BaseService.BEAN_ID);
			// User user = baseService.get(User.class,
			// sessionObject.getUserId());
			// user.setRoleId(sessionObject.getRoleId());
			// baseService.update(user);
			// }

			// 注销日志 杨向阳
			LogService logService = SpringBeanFactory.getBean(LogService.BEAN_ID);
			logService.saveLog(Constant.BIZ_TYPE_001, Constant.LOG_TYPE_02, "用户" + sessionObject.getUserId() + "注销。", sessionObject.getUserId(), sessionObject.getUserName(), context.getRequest().getRemoteAddr());

			// 保存当前角色，作为下一次登陆的首选角色
			if (sessionObject != null) {
				TSysUser sysUser = logService.get(TSysUser.class, sessionObject.getUserId());
				sysUser.setRoleId(sessionObject.getRoleId());
				logService.update(sysUser);
			}

			// 移除SessionObject对象
			context.getRequest().getSession().removeAttribute(Constant.SESSION_OBJECT);
			// 清除session
			context.getRequest().getSession().invalidate();
		}
	}

	/**
	 * 修改密码
	 * 
	 * @param context
	 */
	public void changePassword(IActionContext context) {

		// 1.取得用户、原密码、新密码
		String userId = context.getElementValue("Editor_UserId");
		String oldPwd = StringUtil.getString(context.getCommandParameterValue("oldPswd"));
		String newPwd = StringUtil.getString(context.getCommandParameterValue("newPswd"));

		// 调用业务逻辑
		LoginService loginService = SpringBeanFactory.getBean(LoginService.BEAN_ID);

		try {
			loginService.updatePassword(userId, oldPwd, newPwd);
			this.hintInfoMessage("密码修改成功。");
		} catch (BaseCheckedException e) {
			this.hintErrorMessage(e.getMessage());
		}

	}
}
